<template lang="html">
  <article id="views-personal">
    <PersonalHeader
      :isCoach="isCoach"
      :userInfo="userInfo"
      :memberInfo="memberInfo"
      v-on:scanQRCode="scanQRCode"
      :class="{ isFilter: isShowPanel }"
    ></PersonalHeader>
    <CoachEntries
      v-if="isCoach"
      v-on:applyForCourse="applyForCourse"
      :info="memberInfo"
      :course="latestCourse"
      :class="{ isFilter: isShowPanel }"
    ></CoachEntries>
    <MemberEntries
      v-else
      :info="memberInfo"
      :class="{ isFilter: isShowPanel }"
    ></MemberEntries>
    <RegisterPannel
      v-on:submitForm="submitForm"
      v-if="isShowPanel"
    ></RegisterPannel>
    <ApplyPannel
      :stores="storeList"
      v-on:hidePannel="isApply = false"
      v-if="isApply"
    ></ApplyPannel>
  </article>
</template>

<script>
import superagent from 'superagent'
import authMiddleware from '@/lib/auth-middleware'
import utils from '@/lib/utils'

export default {
  name: 'PagePersonal',
  components: {
    PersonalHeader: require('@/components/personal/header'),
    MemberEntries: require('@/components/personal/entries-member'),
    CoachEntries: require('@/components/personal/entries-coach'),
    RegisterPannel: require('@/components/common_register_panel/register'),
    ApplyPannel: require('@/components/common_register_panel/apply'),
  },
  data(){
    return {
      memberInfo: {},
      latestCourse: null,
      storeList: [],
      isShowPanel: false,
      isApply: false
    }
  },
  computed: {
    userInfo(){
      return this.$store.state.user.userInfo
    },
    isCoach(){
      if(this.memberInfo.hasOwnProperty('isCoach')){
        return this.memberInfo.isCoach
      }
      return false
    }
  },
  methods: {
    applyForCourse(){
      this.isApply = true
    },
    submitForm(form){
      this.setMoreUserInfo(form)
      .then(data => {
        utils.toast('个人信息设置成功')
        this.isShowPanel = false
      })
      .catch(e => {
        if(!!e && !!e.errMsg){
          utils.modal({
            title: '提交失败',
            desc: e.errMsg[0],
          })
        }
      })
    },
    setMoreUserInfo({ age, phone, position, height }){
      return new Promise((resolve, reject) => {
        superagent.post('/api/member/set_user_info')
          // .set('content-type', 'form-data')
          .type('form-data')
          .send({
            age,
            height,
            position,
            mobile: phone
          })
          .use(authMiddleware())
          .end((err, res) => {
            if(res.ok){
              resolve(res.body.data)
            } else {
              if(!!res.body.data){
                reject(res.body.data)
              } else {
                reject(new Error('setMoreUserInfo error'))
              }
            }
          })
      })
    },
    getMemberInfo(){
      return new Promise((resolve, reject) => {
        superagent.get('/api/member/userinfo')
          .use(authMiddleware())
          .end((err, res) => {
            if(res.ok){
              resolve(res.body.data)
            } else {
              if(!!res.body.data){
                reject(res.body.data)
              } else {
                reject(new Error('getMemberInfo error'))
              }
            }
          })
      })
    },
    scanQRCode(){
      this.$store.dispatch('wxScanCode', this.verifyCode)
    },
    verifyCode(code){
      this.requestForVerify(code)
      .then(data => {
        utils.modal({
          title: "验证成功",
          desc: "学员二维码已通过验证"
        })
      })
      .catch(e => {
        if(!!e && e.hasOwnProperty('errCode')){
          let title = "验证失败",
              errorInfo = ''
          switch (e.errCode) {
            case -1:
              errorInfo = '解码有错'
              break;
            case -2:
              errorInfo = '扫码人员不是本课程的老师'
              break;
            case -3:
              errorInfo = '该学员已签到'
              break;
            case -4:
              errorInfo = '该学员不存在'
              break;
            case -5:
              errorInfo = '该课程不存在'
              break;
            case -6:
              errorInfo = '该教练不存在'
              break;
            case -7:
              errorInfo = '该教练的用户信息不存在'
              break;
            case -8:
              errorInfo = '该学员未购买本课程'
              break;
            case -9:
              errorInfo = '缺少参数'
              break;
          }
          utils.modal({
            title,
            desc: errorInfo
          })
        }
      })
    },
    requestForVerify(code){
      return new Promise((resolve, reject) => {
        superagent.post('/api/subject/verifyQR')
          .query({ verCode: code })
          .use(authMiddleware())
          .end((err, res) => {
            if(res.ok){
              resolve()
            } else {
              if(!!res.body.data){
                reject(res.body.data)
              } else {
                reject(new Error('requestForVerify error'))
              }
            }
          })
      })
    },
    getCoachInfo(coachId){
      return new Promise((resolve, reject) => {
        superagent.post('/api/coach/info')
          .query({ coachId })
          .use(authMiddleware())
          .end((err, res) => {
            if(res.ok){
              resolve()
            } else {
              if(!!res.body.data){
                reject(res.body.data)
              } else {
                reject(new Error('getCoachInfo error'))
              }
            }
          })
      })
    },
    getLatestCourse(coachId){
      return utils.requestFactory({
        url: `/api/subject/coach/${coachId}`,
        type: 'post',
        params: {
          // startAfter: 1601134889
          startAfter: Math.floor(Date.now()/1000)
        }
      })
    },
    getStoreList(){
      return utils.requestFactory({
        url: `/api/store/index`,
        type: 'post'
      })
    },
    storeListFilter(stores){
      let arr = []
      stores.forEach(item => {
        let newItem = {
          value: item.storeName,
          id: item.storeId
        }
        arr.push(newItem)
      })
      return arr
    }
  },
  created(){
    this.getMemberInfo()
    .then(data => {
      this.memberInfo = data
      if(!data.hasUserInfo){
        this.isShowPanel = true
      }
      if(data.isCoach){
        return this.getLatestCourse(data.coachId)()
      } else {
        return Promise.resolve(false)
      }
    })
    .then(data => {
      if(data && data.records.length > 0){
        this.latestCourse = data.records[0]
      }
    })
    .catch(e => {
      console.warn(e);
    })

    this.getStoreList()()
    .then(data => {
      let stores = data.stores
      if(!utils.isArray(stores)) throw new Error('storeList is not an array')
      this.storeList = this.storeListFilter(stores)
    })
    .catch(e => {
      console.warn(e);
    })

  }
}
</script>

<style lang="scss" scoped>
#views-personal{
  width: 100%;
  min-height: 100%;
  background: #343437;
  .isFilter{
    filter: blur(10px);
  }
}
</style>
